<template>
	<div class="upload">
		<ul class="list" @click="clickUpload" @dblclick="dblclickUpload" v-if="!isUeditor">
			<draggable :list="fileList" 
			:tag="'div'" 
			:handle="sortOptions.handle" 
			:animation="sortOptions.animation" @update="dragEnd">
				<li :class="(item.url != '')?'full':'empty'" v-for="(item, index) in fileList" :key="index">
					<img :src="domain + item.url" v-if='item.url != ""'>
					<span class="icon iconfont icon-close" v-if='item.url != ""' @click.stop="delPic(item, index)"></span>
					<span class="icon iconfont icon-nopic" v-if='item.url == ""'></span>
				</li>
			</draggable>
			<li class="empty" v-for="(item, index) in (limit-fileList.length)" :key="index+10">
				<span class="icon iconfont icon-nopic"></span>
			</li>
		</ul>
		<!-- 上传窗口 开始 -->
		<el-dialog title="插入图片" :visible.sync="uploadDialogVisible" width="754px" append-to-body>
			<template>
				<el-tabs v-model="activeName" type="card" @tab-click="handleClick">
					<el-tab-pane label="图片管家" name="list">
						<div class="choose-category">
							<el-select v-model="checkAlbumCategory" filterable placeholder="请选择分类" style="width: 480px;" @change="getAlbumByCategory()">
								<el-option v-for="(item, index) in albumCategoryList" :key="index" :label="item.cat_name" :value="item.cat_id"></el-option>
							</el-select>
							<span>请从您的图片管家中点击选择图片</span>
						</div>
						<ul class="list" style="min-height: 45px" 
						v-loading="loading"
						element-loading-text="拼命加载中"
						element-loading-spinner="el-icon-loading">
							<li :class="(checkSelected(item))?'selected':''" v-for="(item, index) in albumListByCategory" :key="index" @click="selectPic(item)">
								<img :src="domain + item.album_path" v-if='item.album_path != ""'>
								<span class="icon iconfont icon-selected" v-if='checkSelected(item)'></span>
							</li>
						</ul>
						<div style="clear: both"></div>
						<div class="page">
							<el-pagination
							@current-change="handleCurrentChange"
							layout="prev, pager, next"
							:background="true"
							small
							:page-size="20"
							:total="pagination.count">
							</el-pagination>
							<div class="page-count">共{{ pagination.count }}张</div>
						</div>
					</el-tab-pane>
					<el-tab-pane label="本地电脑" name="local">
						<el-form label-width="100px">
							<el-form-item label="选择相册" prop="data.album_id">
								<el-select v-model="checkAlbumCategory" filterable placeholder="请选择分类" style="width: 480px;">
									<el-option v-for="(item, index) in albumCategoryList" :key="index" :label="item.cat_name" :value="item.cat_id"></el-option>
								</el-select>
								<el-button type="primary" @click="clickAlbum()">创建新相册</el-button>
							</el-form-item>
								<!-- https://jsonplaceholder.typicode.com/posts/ -->
								<!-- http://super.ac.com/album/upload -->
							<el-form-item label="上传图片" prop="data.album_id">
								<el-upload
								ref="upload"
								class="upload-demo"
								:action="domain + '/' + $api.uploadAlbum"
								name="UploadForm[file]"
								multiple
								list-type="picture"
								:on-progress="handleProgress"
								:before-upload="beforeUpload"
								:on-success="handleSuccess"
								:on-error="handleError"
								:limit="limit - fileList.length"
								:on-exceed="handleExceed"
								:show-file-list="false"
								:with-credentials="true"
								:data="{'catId': cat_id, 'appid': this.appid}"
								:disabled="isdisabled"
								:auto-upload="true">
									<el-button size="small" type="primary" style="width: 480px">选择图片并上传...</el-button>
									<div slot="tip" class="el-upload__tip">只支持上传jpg/png/gif文件，且不超过{{ maxSize }}MB</div>
								</el-upload>
							</el-form-item>
						</el-form>
						<div class="progress-list" ref="progress" v-if="progressShow">
							<div v-for="(item, index) in progress" :key="index">
								<div class="name">{{ item.name }}</div>
								<el-progress :percentage="item.percentage"></el-progress>
								<div class="status" v-html="item.status"></div>
							</div>
						</div>
					</el-tab-pane>
					<div class="uploaded">
						<h6>要插入的图片（{{ uploadList.length }}/{{ limit - fileList.length }}）
							<span class="icon iconfont icon-tuozhuai">可通过拖拽调整图片顺序</span>
							<span style="margin-left: 142px">
								选择尺寸:
								<el-select v-model="selectSize" placeholder="请选择图片尺寸" size="mini">
									<el-option
									v-for="item in imgSize"
									:key="item.size"
									:label="item.label"
									:value="item.size">
									</el-option>
								</el-select>
							</span>
						</h6>
						<draggable class="list" :list="uploadList" 
						:tag="sortOptions.tag" 
						:handle="sortOptions.handle" 
						:animation="sortOptions.animation" @update="dragEnd">
							<li class="full" v-for="(item, index) in uploadList" :key="index+10">
								<img :src="domain + item.url">
								<span class="icon iconfont icon-close" @click="handleRemove(item, index)"></span>
							</li>
						</draggable>
						<ul class="list">
							<li class="empty" v-for="(item, index) in (limit-fileList.length-uploadList.length)" :key="index+20">
								<span class="icon iconfont icon-nopic"></span>
							</li>
						</ul>
					</div>
					<el-button type="primary" class="insert" @click="insertPic">插入图片</el-button>
				</el-tabs>
			</template>
		</el-dialog>
		<!-- 上传窗口 结束 -->

		<!-- 创建相册 开始 -->
		<el-dialog title="创建新相册" :visible.sync="albumDialogVisible" width="500px" append-to-body>
			<el-form :model="albumForm" :rules="rules" ref="albumForm" label-width="100px">
				<el-form-item label="相册名称" prop="data.cat_name" style="width: 378px;">
					<el-input v-model="albumForm.data.cat_name" placeholder="相册名称"></el-input>
				</el-form-item>
				<el-form-item label="访问权限" prop="data.state" v-if='false'>
					<el-radio-group v-model="albumForm.data.state">
						<el-radio :label="1">不公开</el-radio>
						<el-radio :label="2">公开</el-radio>
						<el-radio :label="3">密码</el-radio>
					</el-radio-group>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="albumDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="submitForm('albumForm')" :disabled='albumForm.submitLock'>
					确 定 <span class="el-icon-loading" v-if='albumForm.submitLock'></span>
				</el-button>
			</div>
		</el-dialog>
		<!-- 创建相册 结束 -->
	</div>
</template>

<script>
import draggable from 'vuedraggable'
let clickTime//单击显示相册选择，双击显示本地上传，此变量为了避免单击、双击冲突
export default {
	props: ['domain', 'appid', 'limit', 'fileList', 'maxSize', 'field', 'isUeditor'],//limit最多上传多少张图片，fileList已经存在的图片，maxSize最大体积, action上传域, field需要操作的字段
	data() {
		return {
			/*拖拽插件参数*/
			sortOptions: {
				tag:'ul',//拖动句柄
				handle:'.full',//拖动句柄
				animation: 80,//拖拽排序时，动画的多度时长
			},
			// fileList: [
			// 	{
			// 		name: 'food.jpeg',
			// 		url: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg'
			// 	},
			// 	{
			// 		name: 'food.jpeg',
			// 		url: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1560679288329&di=172c2c82297e0370c719376481a3efd1&imgtype=0&src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2Ff47f57c43ebfab555a3e42938d75afc8540b1a3d34124-CXO8Sg_fw658'
			// 	}
			// ],
			selectSize: '750',
			imgSize: [
				{
					'label': '原始尺寸',
					'sizeName': 'origin',
					'size': 'origin',//后台的文件夹名称就是这个命名
				},//origin
				{
					'label': '70*70',
					'sizeName': 'mini',
					'size': '70',
				},//mini_img
				{
					'label': '300*300',
					'sizeName': 'thumb',
					'size': '300',
				},//thumb_img
				{
					'label': '750*750',
					'sizeName': 'big',
					'size': '750',
				},//big_img
				{
					'label': '1500*1500',
					'sizeName': 'large',
					'size': '1500',
				},//large_img
			],
			activeName: 'list',
			loading: false,//相册加载
			progressShow: false,//进度条框 默认不显示
			progress: [],//进度条
			albumListByCategory: [],//图片管家，选择相册的图片列表
			pagination: {
				count: 0,
				currPage: 1,
				pageSize: 20
			},//图片管家 分页
			uploadList: [],//上传成功的图片列表
			totalSelect: 0,//每次共选择的数量
			success: 0,//每次上传成功的数量
			fail: 0,//每次上传失败的数量
			uploadDialogVisible: false,//上传图片弹框 显示状态
			albumDialogVisible: false,//创建相册弹框 显示状态
			/*相册列表数据*/
			albumCategoryList: [],
			/*选择相册*/
			cat_id: '',
			/*创建相册数据*/
			albumForm: {
				submitLock: false,
				data: {
					cat_name: ''
				}
			},
			rules: {
				data: {
					cat_name: [
						{ required: true, message: '请输入相册名称', trigger: 'blur' },
						{ min: 1, max: 16, message: '长度在 1 到 16 个字符', trigger: 'blur' }
					]
				}
			}
		};
	},
	components: {
		draggable,
	},
	created: function() {
		/*获取所有相册*/
		// this.getAlbumCategory()
	},
	methods: {
		/*获取所有相册*/
		getAlbumCategory: function(){
			this.$baseURL(this.domain)
			this.$get(this.$api.albumCategoryList, {
				appid: (this.appid != '')?this.appid:''
			}).then(res => {
				if(res.data.code === 0){
					if(res.data.data != undefined){
						this.albumCategoryList = res.data.data
						this.cat_id = res.data.data[0].cat_id//默认选择第一个相册
						/*如果当前选项卡是 图片管家的话，且有相册，取出第一个相册的图片，便于选择*/
						if(this.activeName == 'list'){
							this.getAlbumByCategory()
						}
					}
				}
			})
			.catch(err => {})
			.finally(() => {})
		},
		/*根据相册ID选择一个相册的图片*/
		getAlbumByCategory(page=1){
			this.loading = true
			this.$baseURL(this.domain)
			this.$post(this.$api.albumList, {
				page: page,
				cat_id: this.checkAlbumCategory,
				appid: (this.appid != '')?this.appid:''
			}).then(res => {
				// console.log(res.data.data);
				/*成功*/
				if(res.data.code == 0){
					if(res.data.data.list != undefined){
						this.albumListByCategory = []
						this.albumListByCategory = res.data.data.list
						this.pagination = res.data.data.pageInfo
						this.loading = false
					}
				}else{
					this.$message({
						showClose: true,
						message: res.data.info,
						type: 'error'
					});
				}
				this.albumForm.submitLock = false;
			});
		},
		/*单击上传图片 显示相册管家窗口*/
		clickUpload: function(){
			if(this.limit > this.fileList.length){
				clearTimeout(clickTime)
				clickTime = setTimeout(() => {
					this.activeName = 'list'
					this.uploadDialogVisible = !this.uploadDialogVisible
					/*获取所有相册*/
					if(this.albumCategoryList.length == 0){
						this.getAlbumCategory()
					}
	            }, 300);
			}
		},
		/*双击上传图片 显示本地上传窗口*/
		dblclickUpload: function(){
			if(this.limit > this.fileList.length){
				clearTimeout(clickTime)
				this.activeName = 'local'
				this.uploadDialogVisible = !this.uploadDialogVisible
				/*获取所有相册*/
				if(this.albumCategoryList.length == 0){
					this.getAlbumCategory()
				}
			}
		},
		/*点击页码、上页、下页、页面跳转*/
		handleCurrentChange(val) {
			// console.log(`当前页: ${val}`)
			this.loading = true
			this.getAlbumByCategory(val)
		},
		/*相册列表中选择图片*/
		selectPic(file) {
			// console.log(file, 666)
			if(((this.limit - this.fileList.length) - this.uploadList.length) > 0){//判断上传图片是否已满
				/*查看以经上传的列表中，是否已经存在，如果存在去除，如果不存在添加*/
				let has = false//假设不存在
				this.uploadList.forEach((item, index)=>{
					if(item.url == file.album_path){//存在
						has = true
					}
				})
				/*如果不存在，则追加*/
				if(!has){
					this.uploadList.push(
						{
							'name': file.album_name,
							'diffsize': file.diff_size,
							'url': file.album_path
						}
					)
					/*追加到上次队列中，，为了使上传数量一致，比如相册选了2张，一共5张计算，本地只能上传3张*/
					this.$refs.upload.uploadFiles.push({
						name: '',
						url: file.album_path
					})
				}
			}
		},
		/*判断相册列表中的图片是否被选中了*/
		checkSelected(file) {
			let selected = false//假设没有被选中
			this.uploadList.forEach((item, index)=>{
				if(item.url == file.album_path){//存在
					selected = true
				}
			})
			return selected
		},
		/*切换选项卡*/
		handleClick(tab, event) {
			// console.log(tab, event);
			/*如果当前选项卡是 图片管家的话，且有相册，取出第一个相册的图片，便于选择*/
			if(this.activeName == 'list' && this.albumListByCategory.length == 0 && this.albumCategoryList.length != 0){
				this.getAlbumByCategory()
			}
		},
		/*文件超出个数限制时的钩子 超过 limit - fileList.length 的值时触发, 主要是验证*/
		handleExceed(files, fileList) {
			this.$message.warning(`当前限制选择 ${this.limit - this.fileList.length- fileList.length} 个文件，本次选择了 ${files.length} 个文件`);
		},
		/*选择后触发*/
		beforeUpload(file) {
			// console.log(file)
			if(this.cat_id == ''){
				this.$message.warning(`请创建一个相册`)
				return false
			}
			const isJPG = file.type === 'image/jpeg';
			const isGIF = file.type === 'image/gif';
			const isPNG = file.type === 'image/png';
			const isLt2M = file.size / 1024 / 1024 < this.maxSize;
			let pass = true
			this.totalSelect++

			if (!isJPG && !isGIF && !isPNG) {
				pass = false
				this.$message.error('上传头像图片只能是 JPG 或 GIF 或 PNG 格式!');
			}
			if (!isLt2M) {
				pass = false
				this.$message.error(`上传头像图片大小不能超过 ${this.maxSize} MB!`);
			}
			// console.log(file)
			if(pass){
				this.progressShow = true//显示进度条
				/*时刻更新进度数据*/
				this.progress.push({
					uid: file.uid,
					name: file.name,
					status: '准备上传！',//ready
					percentage: 0
				})
			}
			return (isJPG || isGIF || isPNG) && isLt2M;
		},
		/*上传进度*/
		handleProgress(event, file, fileList){
			// console.log(file.status)
			this.progress.forEach((item)=>{
				if(item.uid == file.uid){
					item.percentage = parseInt(event.percent)
					item.status = "正在上传！"//uploading
				}
			})
		},
		/*上传成功后*/
		handleSuccess(res, file, fileList) {
			if(res.code == 0){
				this.success++//增加成功数量
				// this.uploadList = fileList//与上传的顺序一致，可是跟实际上传顺序不符，所以注释掉
				this.uploadList.push(
					{
						'name': res.data.name,
						'diffsize': res.data.diffsize,
						'url': res.data.url
					}
				)
				/*进度条中的状态改成success*/
				this.progress.forEach((item)=>{
					if(item.uid == file.uid){
						item.status = "上传成功！"//success
					}
				})
			}else{
				this.fail++//增加失败数量
				this.$message.warning(res.info);
			}
			/*隐藏进度条*/
			this.hideProgress()
		},
		/*上传失败后*/
		handleError(err, file, fileList) {
			// console.log(file)
			this.fail++//增加失败数量
			this.progress.forEach((item)=>{
				if(item.uid == file.uid){
					item.status = "<span style='color: red'>上传失败！</span>"//fail
					// this.$message.error('[' + file.name + ']上传失败！')
				}
			})
			/*隐藏进度条*/
			this.hideProgress()
		},
		/*
		删除图片
		*/
		handleRemove(file, index) {
			this.uploadList.splice(index, 1)
			this.$refs.upload.uploadFiles.splice(index, 1)
		},
		/*进度条消失*/
		hideProgress(){
			/*如果成功数量+失败数量==此时共选择的数量*/
			if((this.success + this.fail) == this.totalSelect){
				this.totalSelect = 0 //每次共选择的数量
				this.success = 0 //成功数量归零
				this.fail = 0 //失败数量归零
				setTimeout(()=>{
					this.progress = [] //清空进度条数据
					this.progressShow = false //进度条不显示
				}, 2000)
			}
		},
		/*点击创建相册 显示窗口*/
		clickAlbum: function(){
			this.albumDialogVisible = !this.albumDialogVisible
		},
		/*创建相册*/
		submitForm(formName) {
			if(!this.albumForm.submitLock){
				this.$refs[formName].validate((valid) => {
					if (valid) {
						this.albumForm.submitLock = true;
						/*添加、修改分类*/
						let apiUrl = this.$api.addAlbumCategory
						this.$baseURL(this.domain)
						this.$post(apiUrl, {
							AlbumCategory: this.albumForm.data,
							appid: (this.appid != '')?this.appid:''
						}).then(res => {
							// console.log(res.data.data);
							/*成功*/
							if(res.data.code == 0){
								/*在相册列表前追加新相册*/
								this.albumCategoryList.unshift({
									'cat_id': res.data.data.cat_id,
									'cat_name': this.albumForm.data.cat_name
								})
								/*默认选择新建的相册*/
								this.cat_id = res.data.data.cat_id//默认创建新建的相册
								/*删除刚刚创建的相册名称*/
								this.albumForm.data.cat_name = ''
								/*列表相册数据清空，因为相册变成新建的，新建的相册里面肯定是空的*/
								this.albumListByCategory = []

								this.$message({
									showClose: true,
									message: res.data.info,
									type: 'success'
								});
								this.albumDialogVisible = false
							}else{
								this.$message({
									showClose: true,
									message: res.data.info,
									type: 'error'
								});
							}
							this.albumForm.submitLock = false;
						});
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			}
		},
		/*插入上传的图片到父组件*/
		insertPic(){
			if(this.uploadList.length == 0){
				this.$message.error('您没有选择或者上传图片!');
			}else{
				if(this.selectSize != 750){//因为750是跟后台返回的尺寸是一样大的，所以不需要更改尺寸
					for(let i=0; i<this.uploadList.length; i++){
						this.uploadList[i].url = this.getAlbumBySizenum(this.uploadList[i].url, this.uploadList[i].diffsize);
					}
				}
				// console.log(this.uploadList, 8888)
				this.$emit('insertPic', this.uploadList, this.field)//父组件追加上传的图片
				this.uploadDialogVisible = false//关闭上传窗口
				this.uploadList = []//清空已经上传的列表
				this.$refs.upload.uploadFiles = []//清空队列
			}
		},
		/*删除父组件的图片*/
		delPic(item, index){
			// console.log(index)
			this.$emit('delPic', index, this.field)
		},
		/*拖拽完毕，有排序变化才会触发*/
		dragEnd: function(){
			console.log("拖拽完毕")
			// console.log(this.uploadList)
			// console.log(this.fileList)
		},
		/*
		根据原始图片路径 和 不同尺寸的数量，返回对应的尺寸路径
		path 			图片路径
		diffsize 		图片有多个尺寸
		*/
		getAlbumBySizenum: function(path, diffsize){
			let size = this.selectSize//需要返回的尺寸
			let allSize = this.imgSize;//所有配置尺寸
			if((diffsize == 0) || (size == 'origin')){//说明是原图小于70*70 或者需求一个原图 直接返回原图
				if(path.indexOf("origin") != -1){
					return path;
				}else{
					let key1;
					let key2;
					for(let i=0; i<allSize.length; i++){
						key1 = '/' + allSize[i].size + '/';
						key2 = '!!' + diffsize + '_' + allSize[i].size + 'x' + allSize[i].size;
						path = path.replace(new RegExp(key1,'g'), '/origin/')
						path = path.replace(new RegExp(key2,'g'), '')
					}
					return path
				}
			}
			/*需要的尺寸，在所有尺寸的位置*/
			let index = 0;
			for(let i=0; i<allSize.length; i++){
				if(allSize[i].size == size){
					break;
				}
				index++;
			}
			if((index == 0) || (diffsize < index)){//如果需要的尺寸没有的话，直接返回原始图片路径
				if(path.indexOf("origin") != -1){//说明目前就是原始路径 直接返回
					return path;
				}else{
					let key1 = '/' + allSize[diffsize].size + '/';
					let key2 = '!!' + diffsize + '_' + allSize[diffsize].size + 'x' + allSize[diffsize].size;
					path = path.replace(new RegExp(key1,'g'), '/origin/')
					return path.replace(new RegExp(key2,'g'), '')
				}
			}
			if(path.indexOf("origin") != -1){//存在origin
				let key1 = '/origin/';
				let key2 = allSize[diffsize].size + 'x' + allSize[diffsize].size;
				path = path.replace(new RegExp(key1,'g'), '/' + size + '/')
				let arr = path.split('.')
				return arr[0] + '!!' + diffsize + '_' + allSize[index].size + 'x' + allSize[index].size + '.' + arr[1];
			}else{
				let key1;
				let key2;
				for(let i=0; i<allSize.length; i++){
					key1 = '/' + allSize[i].size + '/';
					key2 = allSize[i].size + 'x' + allSize[i].size;
					path = path.replace(new RegExp(key1,'g'), '/' + size + '/')
					path = path.replace(new RegExp(key2,'g'), size + 'x' + size)
				}
				return path
			}
		}
	},
	computed: {
		/*是否禁用上传 当数量已经达到最高数的时候，禁止上传按钮触发*/
		isdisabled: function(){
			if((this.fileList.length+this.uploadList.length)>=this.limit){
				return true
			}
			return false
		},
		/*验证相册是否已经获取到，有了数据才展示,防止直接出现数字，比较尴尬*/
		checkAlbumCategory: {
			get: function () {
				if(this.albumCategoryList.length > 0){
					return this.cat_id
				}else{
					return ''
				}
			},
			set: function (val) {
				this.cat_id = val
			}
		},
	}
};
</script>

<style lang="stylus" scoped>
/deep/ .el-dialog__body
	padding: 12px !important
.choose-category
	margin-bottom: 10px
	span
		margin-left: 10px
		color: #999
.page
	clear: both
	display: flex
	height: 32px
	.el-pagination
		flex: 1
		clear: both
		text-align: right
		margin: 3px 0 5px 0
	.page-count
		line-height: 32px
.list
	display: flex
	flex-wrap: wrap
	li
		width: 68px
		height: 68px
		line-height: 64px
		float: left
		text-align: center
		border: #d6d6d6 1px solid
		box-sizing: border-box
		background-position: center
		background-repeat: no-repeat
		background-size: 60%
		margin: 0 5px 5px 0
		cursor: pointer
		position: relative
		&.selected
			border: #ff7300 1px solid
			box-sizing: inherit
			.icon-selected
				color: #ff7300
				line-height: 16px
				position: absolute
				font-size: 16px
				right: -1px
				bottom: 0px
		&.full
			cursor: move
			span
				display: block
				width: 15px
				height: 15px
				position: absolute
				right: 0
				bottom: 0
				background: #fff
			span:before
				display: block
				line-height: 15px
				font-size: 13px
			span:hover
				color: red
				cursor: pointer
		&.empty
			span:before
				color: #979797
		img
			max-width: 64px
			max-height: 64px
			vertical-align: middle
.uploaded
	h6
		width: 100%
		border-top: 1px solid #ccc
		padding: 15px 0
		font-size: 14px
		display: inline-block
		line-height: 24px
		vertical-align: top
		span
			margin-left: 10px
			font-weight: normal
	width: 100%
	display: block
	overflow: hidden
	ul
		float: left
.insert
	margin-top: 15px
	width: 725px
	
.progress-list
	background: #eefbff
	position: absolute
	top: 0
	left: 20%
	border: 1px solid #ccc
	padding: 10px
	width: 60%
	z-index: 1
	>div
		display: flex
		.name
			width: 80px
			margin-right: 10px
			overflow: hidden
			white-space: nowrap
		.el-progress
			width: 100%
			flex: 1
			display: block
		.status
			width: 70px
	.el-progress__text
		display: none
</style>